<?php
if (!empty($_POST)) {
    if (!session_id()) session_start();
    if (isset($_SESSION['user_state'])) {
        require '../../auth/models/init.php';

        $data['title'] = trim($_POST['title']);
        $data['message'] = trim($_POST['message']);
        $data['userid'] = trim($_SESSION['user_id']);

        $link = db_connect();

        $sql = "INSERT INTO news (`title`, `content`,`userid`) VALUES (?,?,?);";
        $stmt = mysqli_prepare($link, $sql);

        // 绑定参数并执行查询
        mysqli_stmt_bind_param($stmt, "ssi", $data['title'], $data['message'], $data['userid']);
        $textarea = $_POST['textarea']; // 假设表单中的文本区域字段名为 "textarea"
        mysqli_stmt_execute($stmt);

        // 检查插入是否成功
        if (mysqli_stmt_affected_rows($stmt) > 0) {
            echo '<script>';
            echo "alert('添加成功！');";
            echo 'window.history.back();';
            echo '</script>';
        } else {
            echo '<script>';
            echo "alert('添加失败！');";
            echo 'window.history.back();';
            echo '</script>';
        }

        // 关闭预处理语句和数据库连接
        mysqli_stmt_close($stmt);
        mysqli_close($link);
    } else {
        echo "<script>alert('你还没有登录，请先登录！');window.history.back();</script>";
        exit();
    }
}
